package com.hs.controller;

import com.hs.config.MyValues;
import com.hs.config.R;
import com.hs.dao.UserGoodMapper;
import com.hs.entity.Trade;
import com.hs.entity.User;
import com.hs.entity.UserGood;
import com.hs.service.TradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@RequestMapping("trade")
@Controller
public class TradeController {
    @Autowired
    TradeService tradeService;
    @Autowired
    UserGoodMapper userGoodMapper;
    @RequestMapping("insert")
    @ResponseBody
    public R insert(Trade trade, HttpSession session){
        User user = (User) session.getAttribute("user");
        if(trade.getPrice() == null){
            return R.FAILURE("请填写价格",0);
        }
        if(trade.getAmount() == null){
            return R.FAILURE("请填写数量",0);
        }
        if(trade.getGoodId() == null){
            return R.FAILURE("请选择物品",0);
        }
        if(trade.getType() == null){
            return R.FAILURE("请选择类型",0);
        }
        if(trade.getPrice() > MyValues.TRADE_PLATE_PRICE * 1.1 ||  trade.getPrice() < MyValues.TRADE_PLATE_PRICE * 0.9){
            return R.FAILURE("价格不能高于上次收盘价格110%，不能低于上次收盘价格90%,上次收盘价："+ MyValues.TRADE_PLATE_PRICE,MyValues.TRADE_PLATE_PRICE);
        }
        if(trade.getType() == 1 && trade.getPrice() * trade.getAmount() * 100 > user.getFund()){
            return R.FAILURE("持有资金不足,所需资金"+trade.getPrice() * trade.getAmount() * 100,0);
        }
        if(trade.getType() == 2 ){
            UserGood userGoodP = new UserGood();
            userGoodP.setUserId(user.getId());
            userGoodP.setGoodId(trade.getGoodId());
            UserGood userGood = userGoodMapper.getUserGood(userGoodP);
            if(userGood.getAmount() < trade.getAmount() * 100){
                return R.FAILURE("持有物品数量不足",0);
            }
        }
        trade.setUserId(user.getId());
        trade.setUserName(user.getName());
        trade.setAmount(trade.getAmount() * 100);
        int i = tradeService.insert(trade);
        if(i > 0){
            return R.SUCCESS("",i);
        }
        return R.FAILURE("失败",i);
    }


}
